#include <iostream>

bool is_prime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; ++i) {
        if (n % i == 0) return false;
    }
    return true;
}


int largest_prime(int num) {
    if (num < 1000 || num > 9999) return 0;

    int max_prime = 0;
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (i != j) {
                for (int k = 0; k < 4; ++k) {
                    if (k != i && k != j) {
                        int l = 6 - i - j - k;
                        int potential_prime = (num / 1000) * 1000 + (num / 100 % 10) * 100 + (num / 10 % 10) * 10 + (num % 10);
                        if (is_prime(potential_prime) && potential_prime > max_prime) {
                            max_prime = potential_prime;
                        }
                    }
                }
            }
        }
    }
    return max_prime;
}

int main() {
    int num;
    std::cout << "Введите четырёхзначное натуральное число: ";
    std::cin >> num;

    int result = largest_prime(num);
    if (result == 0) {
        std::cout << "0" << std::endl;
    } else {
        std::cout << result << std::endl;
    }

    return 0;
}